package com.zy.edu.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zy.edu.bean.*;
import com.zy.edu.config.SystemParam;
import com.zy.edu.dao.CourseChapterHomeworkDao;
import com.zy.edu.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuangHaiShui
 * @since 2021-08-26
 */
@Service
@Transactional
public class CourseChapterHomeworkServiceImpl extends ServiceImpl<CourseChapterHomeworkDao, CourseChapterHomework> implements CourseChapterHomeworkService {
    @Resource
    ClassinfoService classinfoService;
    @Resource
    CourseChapterHomeworkStuService courseChapterHomeworkStuService;

    @Resource
    HomeworkClassService homeworkClassService;
    @Resource
    UserService userService;
    @Override
    public Map saveOrUpdate(CourseChapterHomework courseChapterHomework,InputParam inputParam) {

        if(StringUtils.isEmpty(courseChapterHomework.getId())){
            courseChapterHomework.setCreateTime(new Date());
            if(StringUtils.isEmpty(courseChapterHomework.getChapterId())){
                //课时为空，则是额外布置的班级作业
                courseChapterHomework.setType(2);
            }else{
                //课时作业
                courseChapterHomework.setType(1);
            }
            courseChapterHomework.setId(UUID.randomUUID().toString().replaceAll("-",""));

            this.baseMapper.insert(courseChapterHomework);
            //若是班级作业，直接发布
            if(courseChapterHomework.getType()==2){
                publish(courseChapterHomework,inputParam);
            }

        }else{

            this.baseMapper.updateById(courseChapterHomework);

        }
        return ResponseInfo.success(null);
    }

    @Override
    public Map list(CourseChapterHomework courseChapterHomework, InputParam inputParam) {
        EntityWrapper<CourseChapterHomework> entityWrapper = new EntityWrapper<CourseChapterHomework>();
        if(!StringUtils.isEmpty(courseChapterHomework.getName())){
            entityWrapper.like("name",courseChapterHomework.getName());
        }
        if(!StringUtils.isEmpty(courseChapterHomework.getChapterId())){
            entityWrapper.eq("chapter_id",courseChapterHomework.getChapterId());
        }
        if(!StringUtils.isEmpty(courseChapterHomework.getClassId())){
            entityWrapper.eq("class_id",courseChapterHomework.getClassId());
        }
        if(courseChapterHomework.getType()!=null){
            entityWrapper.eq("type",courseChapterHomework.getType());
        }
        entityWrapper.eq("status",1);
        entityWrapper.orderBy("create_time",false);

        //查分页
        if(inputParam!=null && inputParam.getPage()!=null && inputParam.getSize()!=null
                && inputParam.getPage()>0 &&  inputParam.getSize()>0){
            Page<CourseChapterHomework> page = new Page<CourseChapterHomework>(inputParam.getPage(), inputParam.getSize());
            List<CourseChapterHomework> tempList = this.baseMapper.selectPage(page,entityWrapper);
            Integer total = this.baseMapper.selectCount(entityWrapper);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("rows", tempList);
            resultMap.put("total", total);
            return ResponseInfo.success(resultMap);
        }else {//查全部
            List<CourseChapterHomework> tempList = this.baseMapper.selectList(entityWrapper);
            return ResponseInfo.success(tempList);
        }

    }

    //仅用于删除课时作业
    @Override
    public Map dele(CourseChapterHomework courseChapterHomework) {
        if(!StringUtils.isEmpty(courseChapterHomework.getId())){
//            courseChapterHomework.setStatus(0);
//            this.baseMapper.updateById(courseChapterHomework);
//            //同时修改学生已提交的相关作业的状态
//            courseChapterHomeworkStuService.updateAllStatus(courseChapterHomework.getId());
            //删除作业数据
            this.baseMapper.deleteById(courseChapterHomework.getId());
            //删除学生提交的数据
            courseChapterHomeworkStuService.deleteByHkId(courseChapterHomework.getId(),null);
            //删除班级关联数据
            homeworkClassService.deleteByHkId(courseChapterHomework.getId(),null);
        }
        return ResponseInfo.success(null);
    }

    //老师已发布作业的删除，不能删除课时作业类型的原始数据
    @Override
    public Map delePublish(CourseChapterHomework courseChapterHomework) {
        if(!StringUtils.isEmpty(courseChapterHomework.getId())){
            //删除作业数据
            if(courseChapterHomework.getType()==2) {
                this.baseMapper.deleteById(courseChapterHomework.getId());
            }
            //删除学生提交的数据
            courseChapterHomeworkStuService.deleteByHkId(courseChapterHomework.getId(),courseChapterHomework.getClassId());
            //删除班级关联数据
            homeworkClassService.deleteByHkId(courseChapterHomework.getId(),courseChapterHomework.getClassId());
        }
        return ResponseInfo.success(null);
    }

    @Override
    public Map getById(CourseChapterHomework courseChapterHomework, InputParam inputParam) {
        if(StringUtils.isEmpty(courseChapterHomework.getId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }
        return ResponseInfo.success(this.selectById(courseChapterHomework.getId()));
    }

    @Override
    public Map publish(CourseChapterHomework courseChapterHomework, InputParam inputParam) {
        //课时作业要发布按钮发布作业
        if(StringUtils.isEmpty(courseChapterHomework.getId())
        ||StringUtils.isEmpty(courseChapterHomework.getClassId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }
        //重新查询，会覆盖掉旧对象里的值，尤其是课时作业类型，classId会变空
        courseChapterHomework = this.selectById(courseChapterHomework.getId());

        //当前用户的信息
        User currentUser = userService.selectById(inputParam.getUserId());
        //只有老师可以发布作业
        if(currentUser.getRoleType().equals(Role.TEACHER)){

            //查询班级下的所有学生
            List<User> userList = userService.getStusByClassId(inputParam);
            if(userList.size()==0){
                return ResponseInfo.error("该班级无学生，无法发布");
            }

            //班级与作业的关联
            if(!checkClsHome(inputParam.getClassId(),courseChapterHomework.getId())) {
                HomeworkClass hc = new HomeworkClass();
                hc.setClassId(inputParam.getClassId());
                hc.setHkId(courseChapterHomework.getId());
                hc.setCreateTime(new Date());
                homeworkClassService.insert(hc);
            }

            List<CourseChapterHomeworkStu> list = new ArrayList<>();
            for (User user : userList) {
                //若该学生已有作业数据，则不发布
                if(!checkStuHome(user.getId(),courseChapterHomework.getId())) {
                    CourseChapterHomeworkStu stu = new CourseChapterHomeworkStu();
                    stu.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    stu.setHkId(courseChapterHomework.getId());
                    stu.setUserId(user.getId());
                    stu.setClassId(inputParam.getClassId());
                    stu.setCourseId(courseChapterHomework.getCourseId());
                    stu.setChapterId(courseChapterHomework.getChapterId());
                    stu.setCreateTime(new Date());
                    stu.setStatus(1);

                    list.add(stu);
                }
            }
            if(list.size()>0) {
                courseChapterHomeworkStuService.insertBatch(list);
                return ResponseInfo.success("发布作业成功");
            }else{
                return ResponseInfo.error("改作业已发布过");
            }

        }else {
            return ResponseInfo.error(SystemParam.ERROR_AUTH);
        }
    }

    @Override
    public Map listByCls(CourseChapterHomework courseChapterHomework, InputParam inputParam) {
        //
//        User temp = userService.selectById(inputParam.getUserId());
        List<Classinfo> classinfoList = classinfoService.findByUserId(inputParam.getUserId());
        String clsStr ="(";
        for (Classinfo classinfo : classinfoList) {
            clsStr+="'"+classinfo.getId()+"',";
        }
        clsStr = clsStr.substring(0,clsStr.length()-1);
        clsStr+=")";
        inputParam.setTempStr(clsStr);
        if(clsStr.length()<5){
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("rows", null);
            resultMap.put("total", 0);
            return ResponseInfo.success(resultMap);
        }

        if(inputParam!=null && inputParam.getPage()!=null && inputParam.getSize()!=null
                && inputParam.getPage()>0 &&  inputParam.getSize()>0){
            Page<CourseChapterHomework> page = new Page<>(inputParam.getPage(), inputParam.getSize());
            List<CourseChapterHomework> tempList = this.baseMapper.getByClsId(page,inputParam);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            //统计每个作业学生已提交的数量
            for (CourseChapterHomework hw : tempList) {
                int countSub = courseChapterHomeworkStuService.countByClsId(hw.getHclass(), true, hw.getId(),false);
                hw.setCountSub(countSub);
                int count = courseChapterHomeworkStuService.countByClsId(hw.getHclass(), false, hw.getId(),false);
                hw.setCount(count);
                int countScore = courseChapterHomeworkStuService.countByClsId(hw.getHclass(), false, hw.getId(),true);
                hw.setCountScore(countScore);
            }
            resultMap.put("rows", tempList);
            resultMap.put("total", page.getTotal());
            return ResponseInfo.success(resultMap);
        }else {

            return ResponseInfo.success(null);
        }
    }



    //查询学生是否有布置该作业
    private boolean checkStuHome(String userId,String hkId){
        EntityWrapper<CourseChapterHomeworkStu> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("hk_id",hkId);
        entityWrapper.eq("user_id",userId);
        List<CourseChapterHomeworkStu> list = courseChapterHomeworkStuService.selectList(entityWrapper);
        if(list.size()>0){
            return true;
        }else {
            return false;
        }
    }
    //查询班级是否有布置该作业
    private boolean checkClsHome(String clsId,String hkId){
        EntityWrapper<HomeworkClass> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("hk_id",hkId);
        entityWrapper.eq("class_id",clsId);
        List<HomeworkClass> list = homeworkClassService.selectList(entityWrapper);
        if(list.size()>0){
            return true;
        }else {
            return false;
        }
    }


}
